<?php


namespace app\api\controller\traits\coupon_order;

use api\channel\jutuike\FoodUnion;
use api\channel\jutuike\TravelUnion;
use app\common\facade\auth\Auth;
use app\common\service\auth\AuthApiService;
use app\common\service\auth\AuthOpenService;
use app\common\service\coupon\CouponBrandService;
use app\model\AgentChannel;
use app\model\ChannelServDiscount;
use app\model\CouponBrandType;
use app\model\CouponCate;
use app\model\CouponBrand;
use app\model\CouponProduct;
use app\model\CouponProductChannel;
use app\Query;
use think\facade\App;
use think\facade\Cache;
use think\Request;

trait Coupon
{


    /**
     * 获取分类和品牌信息
     * @access public
     * @return \think\response\Json
     */
    public function getCateAndSubBrand()
    {
        $cacheTag = 'getCateAndSubBrand_Tag';

        $cacheKey = 'getCateAndSubBrand'.Auth::agentId().'cache';
        $cache = Cache::get($cacheKey);

        if (!empty($cache) && (input('channel') != AgentChannel::YMHC_ADMIN_CHANNEL)) {
            return success('', $cache);
        }

        $datas = CouponCate::query()
            ->where('status', CouponCate::STATUS_ACTIVE)
            ->order('sort desc, updated_at desc')
            ->withoutField('deleted_at, mark, created_at, updated_at, status')
            ->select()
            ->toArray();

        $allBrands = (new CouponBrandService())->effectiveBrand();

        $allBrandsQuery = collect($allBrands);

        foreach ($datas as $key => &$data) {
            $data['couponBrand'] = [];
            $brands = $allBrandsQuery
                ->where('cate_id', $data['id'])
                ->toArray();
//            //判断渠道是否配置出行
            if (count($brands) != 0) {
                $data['couponBrand'] = array_values($brands);
            } else {
                unset($datas[$key]);
            }
        }

        $res = array_values($datas);

        //缓存标签
        Cache::tag($cacheTag)->set($cacheKey, $res, 3600*24*1);

        return success('', $res);
    }

    /**
     * 获取分类和品牌信息
     * @access public
     * @return \think\response\Json
     */
    public function getCateAndSubBrandOld()
    {
        $auth = Auth::instance();
        $cate_field = '';
        $brand_field = '*';
        if ($auth instanceof AuthOpenService) {
            $cate_field = 'id, name';
            $brand_field = 'id, name';
        }
        $datas = CouponCate::query()
            ->where('status', CouponCate::STATUS_ACTIVE)
            ->order('sort desc, updated_at desc')
            ->field($cate_field)
            ->withoutField('deleted_at, mark, created_at, updated_at, status')
            ->select()
            ->toArray();
        foreach ($datas as $key => &$data) {
            $data['couponBrand'] = [];
            $brands = CouponBrand::query()
                ->where('status', CouponBrand::STATUS_ACTIVE)->hasWhere('productChannel', function ($query) {
                    $query->where('status', CouponProductChannel::STATUS_ACTIVE)
                        ->where('butt', CouponProductChannel::BUTT_ACTIVE)
                        ->where('sku_type', CouponProductChannel::SKU_TYPE_ZC)
                        ->where('relate_state', CouponProductChannel::RELETE_STATE_YPP)
                        ->where('shelf_state', CouponProductChannel::RELETE_STATE_YPP)
                        ->where('type', '<>', CouponProductChannel::TYPE_JTK);
                }, $brand_field)->join('coupon_brand_cate_relation', 'coupon_brand_cate_relation.brand_id = coupon_brand.id')
                ->where('coupon_brand_cate_relation.cate_id', $data['id'])
                ->where('coupon_brand.status', CouponBrand::STATUS_ACTIVE)
                ->order('coupon_brand.sort desc, coupon_brand.updated_at desc')
                ->select()->each(function (CouponBrand $couponBrand) use ($auth) {
                    if (!$auth instanceof AuthOpenService) {
                        $couponBrand->append(['sale_price_discount']);
                    }
                })->toArray();
            if ($auth instanceof AuthApiService) {
                /**
                 * @var AgentChannel $agentChannel
                 */
                $agentChannel = $this->request->agentChannel;
                $couponBrand = new CouponBrand();
                $travelUnion = $couponBrand->getJutuikelList([
                    //'type' => CouponBrand::TYPE_TRAVEL,
                    'status' => CouponBrand::STATUS_ACTIVE,
                    'serv_type' => PRODUCT_TRAVEL_OIL_SERV,
                    'field' => 'act_id, name, act_name, image_url, belong, type, discount_logo, subtitle_type, subtitle, icon'
                ])->toArray();
                $foodUnion = $couponBrand->getJutuikelList([
                    //'type' => $couponBrand::TYPE_UNION_FOOD,
                    'status' => $couponBrand::STATUS_ACTIVE,
                    'serv_type' => PRODUCT_FOOD_SHOP_SERV,
                    'field' => 'act_id, name, act_name, image_url, belong, type, discount_logo, subtitle_type, subtitle, icon'
                ])->toArray();
                $diyModules = [
                    [
                        'name' => '日常出行',
                        //'const' => TravelUnion::TRAVELSTATICDATA,
                        'const' => $travelUnion,
                        'serv_type' => PRODUCT_TRAVEL_OIL_SERV,
                    ],
                    [
                        'name' => '餐饮美食',
                        //'const' => FoodUnion::PRODUCTS,
                        'const' => $foodUnion,
                        'serv_type' => PRODUCT_FOOD_SHOP_SERV,
                    ]
                ];
                foreach ($diyModules as $diyModule) {
                    $hasType = $agentChannel->hasServType($diyModule['serv_type']); //判断是否有出行的权限
                    if ($data['name'] == $diyModule['name'] && $hasType) {
                        $brands = $brands ? $brands : [];
                        $brands_temp = $diyModule['const'];
                        if ($brands) {
                            foreach ($brands as $brand) {
                                array_push($brands_temp, $brand);
                            }
                        }
                        $brands = $brands_temp;
                    }
                }
            }
            //判断渠道是否配置出行
            if (count($brands) != 0) {
                $data['couponBrand'] = $brands;
            } else {
                unset($datas[$key]);
            }
        }
        return success('', array_values($datas));
    }

    /**
     * 权益-----获取商品详情页信息
     * @access public
     * @returns \think\response\Json
     */
    public function getProductChannlDetail(Request $request)
    {
        $brand_id = $request->param('brand_id');
        if (empty($brand_id)) {
            return fail('请传入品牌id');
        }
        $auth = Auth::instance();
        $agent_id = 0;
        //H5端
        if ($auth instanceof AuthApiService) {
            $agent_id = Auth::agentId();
        }
        //查询品牌是否存在
        $brand = CouponBrand::where('id', $brand_id)->findOrEmpty();
        if ($brand->isEmpty()) {
            return fail('品牌不存在');
        }
        $brandMode = new CouponBrand();
        $rows = $brandMode->getProductChannlDetail($brand_id, $agent_id);
        return success('请求成功！', compact('rows'));
    }

    /**
     * 获取品牌的充值类型 --暂不使用
     * @access public
     * @return \think\response\Json
     * 暂不使用
     */
    public function getBrandSubBrandType()
    {
        $auth = Auth::instance();
        $brandOrder = 'sort desc';
        $typeOrder = 'sort desc';
        if ($auth instanceof AuthOpenService) {
            $brandOrder = 'id asc';
            $typeOrder = 'id asc';
        }
        $couponBrandTypes = CouponBrand::query()->where('status', CouponBrand::STATUS_ACTIVE)
            ->with(['brandType' => function ($query) use ($typeOrder) {
                $query->where('status', CouponBrandType::STATUS_ACTIVE)
                    ->field('id, name, brand_id')
                    ->hidden(['brand_id'])
                    ->order($typeOrder);
            }])->where('id', 'in', function ($sql) {
                $sql->name('coupon_product_channel')->field('brand_id')
                    ->where('butt', CouponProductChannel::BUTT_ACTIVE)
                    ->where('type', '<>', CouponProductChannel::TYPE_JTK)
                    ->where('status', CouponProductChannel::STATUS_ACTIVE)
                    ->where('shelf_state', CouponProductChannel::SHELF_STATE_SZ)
                    ->where('relate_state', CouponProductChannel::RELETE_STATE_YPP);
            })->field('id, name')
            ->order($brandOrder)
            ->select();
        return success('success', $couponBrandTypes);
    }

    /**
     * 获取充值类型下的面额  --暂不使用
     * @access public
     * @return \think\response\Json
     * 暂不使用
     */
    public function getBrandTypeSubproduct()
    {
        $auth = Auth::instance();
        $brandTypeOrder = 'sort desc';
        $productOrder = 'sort desc';
        if ($auth instanceof AuthOpenService) {
            $brandTypeOrder = 'id asc';
            $productOrder = 'id asc';
        }
//        $productChannel = CouponProductChannel::query()
//            ->where('butt', CouponProductChannel::BUTT_ACTIVE)
//            ->where('type', '<>', CouponProductChannel::TYPE_JTK)
//            ->where('status', CouponProductChannel::STATUS_ACTIVE)
//            ->where('shelf_state', CouponProductChannel::SHELF_STATE_SZ)
//            ->where('relate_state', CouponProductChannel::RELETE_STATE_YPP)
//            ->select();
//        $query = collect($productChannel);
//        $brand_ids = $query->column('brand_id');
//        $brand_ids = array_unique($brand_ids);
        $couponBrandTypeProduct = CouponBrandType::query()->where('status', CouponBrandType::STATUS_ACTIVE)
            ->with(['product' => function ($query) use ($productOrder) {
                $query->where('status', CouponProduct::STATUS_ACTIVE)
                    ->field('id, name, type_id')
                    ->hidden(['type_id'])
                    ->order($productOrder);
            }])
            //->whereIn('brand_id', $brand_ids)->order($brandTypeOrder)
            ->field('id, name')
            ->select();
        return success('success', $couponBrandTypeProduct);
    }


}